<template>
    <div class="viewo-cell">
        <MaterialResPlayer
            ref="videoPlayerRef"
            mode="h5"
            :material="props.videoData"
            :video-config="videoConfig"
            @play="onPlay"
            @pause="onPause"
            @ended="onEnded"
            @error="onError"
        />
    </div>
</template>

<script setup>
import { computed, onMounted, onBeforeUnmount, nextTick, watch, ref } from 'vue';
import { MaterialResPlayer } from '@yanxiu/player';
import { useRoute } from 'vue-router';
import useReport from '@/hooks/useReport.js';
import { useStore } from 'vuex';

const store = useStore();

const route = useRoute();
const report = useReport();

defineExpose({
    startVideo,
    startRecord,
    playToSpecifiedPoint
})

const props = defineProps({
    videoData: {
        type: Object,
        default: () => {}
    },
    detail: {
        type: Object,
        default: () => {}
    },
    catalogueId: {
        type: [Number, String],
        default: ''
    },
    isBuyPerson: {
        type: Boolean,
        default: false
    }
})

let player = null;

const videoPlayerRef = ref(null);

// 历史位置
const historyLocation = ref(0);

const videoConfig = computed(() => {
    let obj = {}
    if (historyLocation.value) {
        obj.lastPlayTime = historyLocation.value;
        obj.autoplay = true;
    }
    if (props.videoData?.snapshotCover) {
        obj.poster = props.videoData?.snapshotCover;
    }
    return obj
});

// 用户信息和课件信息
const userAndDetail = computed(() => {
    return {currentUser: store.state.currentUser, detail: props.detail};
})

// 获取视频上一次播放位置
function getVideoRecord(userId, resId) {
    G_transmit('hbUserRecord', {
        queries: {
            appId: '100002',
            bizId: route.params.moocId,
            bizType: 'mooc',
            srxUserId: userId,
            resId: resId,
            resSource: 'courseWare'
        },
        silence: true
    }).then((res) => {
        let watchLocation = res.data?.watchLocation || 0;
        historyLocation.value = watchLocation;
        playToSpecifiedPoint(watchLocation);
    })
}

// watch(() => userAndDetail.value, async(val) => {
//     await nextTick();
//     // 用户存在并且课件id存在，获取播放位置
//     if(val?.currentUser?.userId && val?.detail?.courseWareId) {
//         getVideoRecord(val.currentUser.userId, val.detail.courseWareId);
//     }
// }, {deep: true, immediate: true})

watch(() => props.catalogueId, (newVal) => {
    console.log(props.catalogueId, 'watch');
    if (props.videoData?.materialStatus === 'usable' && player) {
        report && report.hbReport(player.currentTime);
    }
    player = null;
    report && report.endReportFn();
    report && report.endWatchTime();
    nextTick(() => {
        if (props.videoData.materialStatus === 'usable') { // 资源可用
            initPlayer();
            if (props.isBuyPerson) {
                startRecord();
            }
        }
    })
}, {
    immediate: true
})


function startVideo (item) {
    if (item.resourceStart > player.duration) {
        G_dispatchEvent('toast', { message: '检测到视频已更换', type: 'error' });
        return;
    }
    if (!player.ended) {
        player.pause();
    }
    // 删除标记
    player.removeAllProgressDot();
    player.currentTime = item.resourceStart;
    if (item.noteType === 1) {
        player.addProgressDot(item.resourceStart);
        player.addProgressDot(item.resourceEnd);
        let duration = item.resourceEnd - item.resourceStart;
        player.addProgressDot(item.resourceStart, duration, { background: 'red' });
    } else {
        player.addProgressDot(item.resourceStart);
    }
}

async function startRecord () {
    await nextTick();
    report.reportFn(route.params.moocId, props.detail.courseWareId, player.currentTime);
}

// 跳转到特定播放点
function playToSpecifiedPoint(data) {
    if (videoPlayerRef.value && player) {
        if (player.play) {
            player.currentTime = data;
            player.play();
        }
    }
}

// 初始化播放器
function initPlayer () {
    player = videoPlayerRef.value.getInstance();
    // 初始化的时候有心跳记录
    if (historyLocation.value) {
        playToSpecifiedPoint(historyLocation.value)
    }
}

function onPlay () {
    console.log('onPlay');
    report.startWatchTime();
}

function onPause () {
    console.log('onPause');
    report.endWatchTime();
}

function onEnded () {
    console.log('onEnded');
    report.endWatchTime();
}

function onError () {
    console.log('onError');
    report.endWatchTime();
}


// onMounted(async () => {
//     await nextTick();
//     if (props.videoData.materialStatus === 'usable') { // 资源可用
//         initPlayer();
//     }
// })

onBeforeUnmount(() => {
    if (props.videoData.materialStatus === 'usable' && player) {
        report.hbReport(player.currentTime);
    }
    player = null;
    report.endReportFn();
    report.endWatchTime();
})

</script>

<style lang="scss" scoped>
.viewo-cell {
    .material-res-player {
        height: 210px;
        
    }
}
</style>